package br.unicap.curativotermosensor;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.net.URL;

import br.unicap.curativotermosensor.utils.NotificacaoUtil;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class Servico extends Service implements Runnable{
	protected static final String URL = "http://192.168.1.5:80/arquivo.txt";
	protected static final String CATEGORIA = "temperatura";
	private static final int segundos = 5;
	private static final int tempoRepetir = 10 * 1000;
	private String arquivo;
	int flag = 0;
	@Override
	public void run() {
		try {
			arquivo = downloadArquivo(URL);
			Log.i(CATEGORIA, arquivo);
			int temp;
			temp = Integer.parseInt(arquivo);
			if(temp>36 && flag==0){
				Log.i(CATEGORIA, arquivo);
				criarNotificacao();
				flag=1;
			}
		} catch (Throwable e) {
			Log.i(CATEGORIA, e.getMessage(),e);
		} finally {
			
		}		
	}
	public String getArquivo(){
		return arquivo=downloadArquivo(URL);
	}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	public void onCreate(){
		agendar(segundos);
	}
	public int onStartCommand(Intent intent, int flags, int startId){
		new Thread(this).start();
		return startId;
	}
	public final String downloadArquivo(String url) {
		try {
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.setDoOutput(false);
			conn.connect();
			InputStream in = conn.getInputStream();
			arquivo = readString(in);
			conn.disconnect();
			return arquivo;
		} catch (MalformedURLException e) {
			Log.e(CATEGORIA, e.getMessage(), e);
		} catch (IOException e) {
			Log.e(CATEGORIA, e.getMessage(), e);
		}
		return null;
	}

	public String doPost(String url, Map<String, Object> params) {
		try {
			String queryString = getQueryString(params);
			String texto = doPost(url, queryString);
			return texto;
		} catch (IOException e) {
			Log.e(CATEGORIA, e.getMessage(), e);
		}
		return url;
	}

	private String doPost(String url, String params) throws IOException {
		Log.i(CATEGORIA, "Http.doPost: " + url + "?" + params);
		URL u = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.connect();
		OutputStream out = conn.getOutputStream();
		byte[] bytes = params.getBytes("UTF8");
		out.write(bytes);
		out.flush();
		out.close();
		InputStream in = conn.getInputStream();
		String texto = readString(in);
		conn.disconnect();
		return texto;
	}
	private String getQueryString(Map<String, Object> params) throws IOException {
		if (params == null || params.size() == 0) {
			return null;
		}
		String urlParams = null;
		Iterator<String> e = (Iterator<String>) params.keySet().iterator();
		while (e.hasNext()) {
			String chave = (String) e.next();
			Object objValor = params.get(chave);
			String valor = objValor.toString();
			urlParams = urlParams == null ? "" : urlParams + "&";
			urlParams += chave + "=" + valor;
		}
		return urlParams;
	}
	private byte[] readBytes(InputStream in) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			byte[] buffer = new byte[1024];
			int len;
			while ((len = in.read(buffer)) > 0) {
				bos.write(buffer, 0, len);
			}
			byte[] bytes = bos.toByteArray();
			return bytes;
		} finally {
			bos.close();
			in.close();
		}
	}
	private String readString(InputStream in) throws IOException {
		byte[] bytes = readBytes(in);
		String texto = new String(bytes);
		return texto;
	}
	private void agendar(int segundos) {
		Intent it = new Intent("ABRIR_SERVICO");
		PendingIntent p = PendingIntent.getService(this, 0, it, 0);
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		c.add(Calendar.SECOND, segundos);
		AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
		long time = c.getTimeInMillis();
		alarme.setRepeating(AlarmManager.RTC_WAKEUP, time, tempoRepetir, p);
		Log.i(CATEGORIA, "Alarme agendado para daqui a " + segundos + " segundos. Repetir a cada " + tempoRepetir);
	}
	protected void criarNotificacao() {
		String mensagemBarraStatus = "Fim do download.";
		String titulo = "Download completo.";
		String mensagem = "Visualizar imagem do download.";
		Class<?> activity = CurativoTermoSensor.class;
		Intent intentMensagem = new Intent(this, activity);
		intentMensagem.putExtra("temp", "teste");
		NotificacaoUtil.create(this, mensagemBarraStatus, titulo, mensagem, R.drawable.ic_launcher, R.drawable.ic_launcher, intentMensagem);
	}
}


